from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sys import maxsize
# 创建对象的基类:
Base = declarative_base()
# 初始化数据库连接:
engine = create_engine('sqlite:///test.db', encoding="utf-8", echo=True)
# 创建session对象:
session = sessionmaker(bind=engine)()

class OrmBase(object):
    def __init__(self,**kwargs):
        if kwargs:
            for k, v in kwargs.items():
                if hasattr(self, k):
                    setattr(self, k, v)

    @staticmethod
    def commit():
        try:
            session.commit()
        except:
            session.rollback()
            raise
        finally:
            session.close()

    @classmethod
    def create(cls, **kwargs):
        try:
            entity = cls(**kwargs)
            session.add(entity)
            session.commit()
            return entity
        except:
            session.rollback()
            raise
        finally:
            session.close()

    @classmethod
    def get(cls, **kwargs):
        '''
        查询方法
        :param kwargs:查询条件 （属性名=属性值）
        :return: 返回Query对象，根据需要做.all()、.first()、.update()等操作
        '''
        try:
                return session.query(cls).filter_by(**kwargs)
        except:
            raise
        finally:
            session.close()

    @classmethod
    def get_page(cls, pageIndex: int = 1, pageSize: int = maxsize, **kwargs):
        try:
            if pageSize == maxsize and pageIndex > 1:
                raise Exception("page参数异常")
            else:
                return session.query(cls).filter_by(**kwargs).limit(pageSize).offset((pageIndex - 1) * pageSize)
        except:
            raise
        finally:
            session.close()

    def delete(self):
        try:
            self.delete()
            session.commit()
        except:
            session.rollback()
            raise
        finally:
            session.close()

